package de.bht.netviz.ipsaver.lookup.service;

import de.bht.netviz.ipsaver.lookup.model.GeoPluginLookupData;
import de.bht.netviz.ipsaver.lookup.model.ILookupData;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * Implementation of the ILookupData interface, using the GeoPlugin 
 * IP Lookup service (http://www.geoplugin.net).
 *
 * @author Marius Hentschel
 * @since  2012/10/24
 */
public class GeoPluginLookupService extends AbstractLookupService {
   /**
    * URL of the web service
    */
   private static final String BASE_URL = "http://www.geoplugin.net/xml.gp";
   
   /**
    * argument name for the IP request
    */
   private static final String ARG_NAME = "ip";
   
   /**
    * Singleton instance
	*/
   private static GeoPluginLookupService instance;
   
   /**
    * Private standard constructor, does nothing.
    */
   protected GeoPluginLookupService() {
      super( BASE_URL, ARG_NAME );
   }
   
   /**
    * Singleton getter (lazy instantiation)
	*/
   public static GeoPluginLookupService getInstance() {
      if( instance == null ) {
	     instance = new GeoPluginLookupService();
      }
	  return instance;
   }

   @Override 
   public ILookupData webserviceLookup( String ip ) {
      try {
         Unmarshaller u = JAXBContext.newInstance(GeoPluginLookupData.class).createUnmarshaller();
         return (GeoPluginLookupData) u.unmarshal( new URL( 
               super.getBaseURL() + ( super.getBaseURL().endsWith("?") ? "" : "?" ) +
               super.getArgName() + "=" + ip  ) );
      } catch (JAXBException | MalformedURLException ex) {
         Logger.getLogger(GeoPluginLookupService.class.getName()).log(Level.SEVERE, null, ex);
      }
      return null;
   }

}